using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WindowsPhonePostClient;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;
namespace LyonMag
{
    public partial class comments : PhoneApplicationPage
    {
        Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        string id = string.Empty;
        string pagename = string.Empty;
        private App app = App.Current as App;
        List<Homepageclass.HomeComments> obj_comments = new List<Homepageclass.HomeComments>();
        public comments()
        {
            try
            {
                InitializeComponent();
              
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (App.appSettingsGuid["accoutid"].ToString() != "test")
            {
                postforum();
            }
            else
            {
                popNickName.IsOpen = true;
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                NavigationContext.QueryString.TryGetValue("id", out id);
                NavigationContext.QueryString.TryGetValue("pagename", out pagename);
                if (pagename == null)
                {
                    for (int i = 0; i < app.lst_Home.Count(); i++)
                    {
                        if (app.lst_Home[i].Id == id)
                        {
                            for (int k = 0; k < app.lst_Home[i].Home_comments.Count(); k++)
                            {

                                obj_comments.Add(new Homepageclass.HomeComments() {Comment_date= app.lst_Home[i].Home_comments[k].Comment_date, Comment_id = app.lst_Home[i].Home_comments[k].Comment_id, Comment_name = app.lst_Home[i].Home_comments[k].Comment_name, Comment_text = app.lst_Home[i].Home_comments[k].Comment_text });
                            }
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < app.lst_files.Count(); i++)
                    {
                        if (app.lst_files[i].Id == id)
                        {
                            for (int k = 0; k < app.lst_files[i].Home_comments.Count(); k++)
                            {

                                obj_comments.Add(new Homepageclass.HomeComments() { Comment_date = app.lst_files[i].Home_comments[k].Comment_date, Comment_id = app.lst_files[i].Home_comments[k].Comment_id, Comment_name = app.lst_files[i].Home_comments[k].Comment_name, Comment_text = app.lst_files[i].Home_comments[k].Comment_text });
                            }
                        }
                    }
                }
                List<Homepageclass.HomeComments> newtest = obj_comments.ToList();
                newtest.Reverse();
                lstForum.ItemsSource = newtest;
                if (App.appSettingsGuid["accoutid"].ToString() != "test")
                {
                    btnLogout.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }

        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            popNickName.IsOpen = false;
            popLogins.IsOpen = false;
            popRigister.Visibility = Visibility.Collapsed;
        }

        private void btnEnter_Click(object sender, RoutedEventArgs e)
        {
            if(txtNickName.Text!="")
            {
           
                postforum();
               
         
            }
            else
            {
                MessageBox.Show("Vous devez saisir un pseudo !");
            }
        }
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

       /// <summary>
       /// login
       /// </summary>
        public void userlogin()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("login", txtUsernamePassword.Text);
           // string heypassord = GetRandomAlphaNumeric;
            string encryptedpassowrd = "a5" + txtPasswordPassword.Password;
            string userpassword = Base64Encode(encryptedpassowrd);
           //  parameters.Add("email", txtUsernamePassword.Text);
            parameters.Add("password", userpassword);

            PostClient proxy = new PostClient(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    //Process the result...
                    string data = e.Result;
                    if (data != "ko")
                    {
                        App.appSettingsGuid["accoutid"] = data.ToString();
                        App.appSettingsGuid.Save();
                        popLogin.IsOpen = false;
                        popNickName.IsOpen = true;
                        popSubmit.IsOpen = false;
                        btnLogout.Visibility = Visibility.Visible;
                       App.appSettingsGuid["username"] = data.ToString();
                       App.appSettingsGuid.Save();
                       postforum();
                       // popAlert.IsOpen = true;
                        
                        //MessageBox.Show("Votre compte a bien été créé. Un email de confirmation vient de vous être envoyé.\n\nPour poster des commentaires avec un compte différent, cliquez sur le bouton de déconnexion qui vient d'apparaître en haut de l'écran");
                    }
                    else
                    {
                       // MessageBox.Show("Login ou mot de passe incorrect (si vous avez oublié votre mot de passe, rendez-vous sur notre site www.lyonmag.com)");
                        txtUserName.Text = txtNickName.Text;
                        popRigister.Visibility = Visibility.Collapsed;

                        popLoginFailed.IsOpen = true;
                        popNickName.IsOpen = false;
                       
                    }

                }
            };
            proxy.DownloadStringAsync(new Uri("http://www.lyonmag.com/win8/login", UriKind.Absolute));
        }
      /// <summary>
      /// post Comment
      /// </summary>
        public void postforum()
        {
            if(App.appSettingsGuid["accoutid"].ToString()!= "test")
            {
               
                Dictionary<string, object> parameters = new Dictionary<string, object>();

                parameters.Add("action", "add_comment");


                parameters.Add("id", id);
                parameters.Add("type", "article");
                if (App.appSettingsGuid["username"].ToString() != "testuser")
                {
                    parameters.Add("name", App.appSettingsGuid["username"].ToString());
                }
                else
                {
                    parameters.Add("name", txtNickName.Text);
                }
                if (App.appSettingsGuid["accoutid"].ToString() == "test")
                {
                    parameters.Add("account_id", string.Empty);
                }
                else
                {
                    parameters.Add("account_id", App.appSettingsGuid["accoutid"].ToString());
                }

                parameters.Add("text", txtComment.Text);

                PostClient proxy = new PostClient(parameters);
                proxy.DownloadStringCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        //Process the result...
                        string data = e.Result;



                        if (data == "0 Ce nom d'utilisateur est r�serv� ou incorrect. Connectez-vous s'il s'agit du votre.")
                        {
                            popLogins.IsOpen = true;
                            popNickName.IsOpen = false;
                        }
                        else
                        {
                            popNickName.IsOpen = false;
                          //  MessageBox.Show(e.Result.ToString());
                            popSecond.IsOpen = true;
                         //   this.NavigationService.GoBack();
                            popNickName.IsOpen = false;
                            popLogin.IsOpen = false;
                            popRigister.Visibility = Visibility.Collapsed;
                            popLogins.IsOpen = false;
                        }




                    }
                };
                proxy.DownloadStringAsync(new Uri("http://www.lyonmag.com/win8/comment", UriKind.Absolute));
            }
            else
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();

                parameters.Add("action", "add_comment");


                parameters.Add("id", id);
                parameters.Add("type", "article");
                parameters.Add("name", txtNickName.Text);
                if (App.appSettingsGuid["accoutid"].ToString() == "test")
                {
                    parameters.Add("account_id", string.Empty);
                }
                else
                {
                    parameters.Add("account_id", App.appSettingsGuid["accoutid"]);
                }

                parameters.Add("text", txtComment.Text);

                PostClient proxy = new PostClient(parameters);
                proxy.DownloadStringCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        //Process the result...
                        string data = e.Result;



                        if (data == "0 Ce nom d'utilisateur est r�serv� ou incorrect. Connectez-vous s'il s'agit du votre.")
                        {
                            popLogins.IsOpen = true;
                            popNickName.IsOpen = false;
                        }
                        else
                        {
                            popSubmit.IsOpen = true;
                            popNickName.IsOpen = false;
                        }




                    }
                };
                proxy.DownloadStringAsync(new Uri("http://www.lyonmag.com/win8/comment", UriKind.Absolute));
            }
           
        }
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
           
            popRigister.Visibility = Visibility.Visible;
            popNickName.IsOpen = false;
            popSubmit.IsOpen = false;
           txtUserName.Text = txtNickName.Text;
           txtUsernamePassword.Text = txtNickName.Text;
          
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationBar.IsVisible = false;
                App.appSettingsGuid["accoutid"] = "test";
                App.appSettingsGuid.Save();
            }
            catch (Exception ex)
            {
                ApplicationBar.IsVisible = false;
                App.appSettingsGuid["accoutid"] = "test";
                App.appSettingsGuid.Save();
                ex.Message.ToString();
            }
        }
        private void btnTryAgain_Click(object sender, RoutedEventArgs e)
        {
            popLogin.IsOpen = false;
            popNickName.IsOpen = false;
            popSubmit.IsOpen = false;
           
            popRigister.Visibility = Visibility.Collapsed;
            this.NavigationService.GoBack();
           
        }

        private void btnLoginCancel_Click(object sender, RoutedEventArgs e)
        {
            popLogin.IsOpen = false;
        }

       
      
        private void btnLoginUser_Click(object sender, RoutedEventArgs e)
        {

            popNickName.IsOpen = false;
            userlogin();
        }
        /// <summary>
        /// User Register
        /// </summary>
        public void userregister()
        {
            try
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("username", txtUserName.Text);
                string userpassword = Base64Encode("a5" + txtPasswor.Password);
                parameters.Add("email", txtEmail.Text);
                parameters.Add("password", userpassword);

                PostClient proxy = new PostClient(parameters);
                proxy.DownloadStringCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {

                        string data = e.Result;




                        if (data == "0 Ce nom d'utilisateur est réservé ou incorrect. Connectez-vous s'il s'agit du votre.")
                        {
                            popLogins.IsOpen = true;
                            popAlert.IsOpen = false;

                            poplogout.IsOpen = false;
                            popNickName.IsOpen = false;
                            popRigister.Visibility = Visibility.Collapsed;

                        }
                        else
                        {


                            App.appSettingsGuid["accoutid"] = data.ToString();
                            App.appSettingsGuid.Save();

                            App.appSettingsGuid["username"] = data.ToString();
                            App.appSettingsGuid.Save();
                            btnCamcelRegister.Click += btnCamcelRegister_Click;
                            popRigister.Visibility = Visibility.Collapsed;
                            popNickName.Visibility = Visibility.Collapsed;
                            btnLogout.Visibility = Visibility.Visible;
                            txtComment.Text = "";
                            popAlert.IsOpen = true;

                        }

                    }
                };
                proxy.DownloadStringAsync(new Uri(" http://www.lyonmag.com/win8/register", UriKind.Absolute));
            }
            catch (Exception ex)
            {

                if (NetworkInterface.GetIsNetworkAvailable() == true)
                {
                    // MessageBox.Show(NetworkInterface.GetIsNetworkAvailable().ToString());
                }
                else
                {
                    MessageBox.Show("Internet Not Availabe", "LyonMag", MessageBoxButton.OK);
                }
            }
        }
        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
          
            popNickName.Visibility = Visibility.Collapsed;
            if(regex.Match(txtEmail.Text.Trim()).Success)
            {
                userregister();
            }
            else
            {
                popEMail.IsOpen = true;
            }
         
        }

        private void btnCamcelRegister_Click(object sender, RoutedEventArgs e)
        {
            popRigister.Visibility = Visibility.Collapsed;
            popLogin.IsOpen = false;
            popNickName.IsOpen = false;
            popSubmit.IsOpen = false;
        }

        private void btnTrynew_Click(object sender, RoutedEventArgs e)
        {
            popNickName.IsOpen = true;
            popLogins.IsOpen = false;
        }

        private void btnLoginnew_Click(object sender, RoutedEventArgs e)
        {
            popLogin.IsOpen = true;
            txtUsernamePassword.Text = txtNickName.Text;
            popLogins.IsOpen = false;
        }

        private void btnLogout_Click(object sender, RoutedEventArgs e)
        {
            App.appSettingsGuid["accoutid"] = "test";
            App.appSettingsGuid.Save();
            poplogout.IsOpen = true;
            btnLogout.Visibility = Visibility.Collapsed;
           // poplogout.IsOpen = false;
        }

        private void popafterregistration_Click(object sender, RoutedEventArgs e)
        {
            popAlert.IsOpen = false;
        }

        private void BtnLogoutNew_Click(object sender, RoutedEventArgs e)
        {
            poplogout.IsOpen = false;
        }

        private void btnCloseSecond_Click(object sender, RoutedEventArgs e)
        {
            popSecond.IsOpen = false;
            this.NavigationService.GoBack();
        }

        private void popValidEmail_Click(object sender, RoutedEventArgs e)
        {
            popEMail.IsOpen = false;
        }

        private void btnFermerloginfailed_Click(object sender, RoutedEventArgs e)
        {
            popLoginFailed.IsOpen = false;
        }
    }
}